<template>
  <div class="body">
    <el-container style="display: flex; justify-content: center; align-items: center; height: 100vh;">
      <div class="main">
        <el-card class="box-card" shadow="hover">
          <div class="clearfix">
            <span>比赛信息修改</span>
          </div>
          <div class="form-container">
            <el-form :model="From" label-width="100px" class="event-form">
              <div>
                <el-form-item label="选择修改项目">
                  <el-select v-model="selectedProjectId" placeholder="请选择项目" @change="handleSelectChange">
                    <el-option v-for="project in newProjectadd" :key="project.id" :label="project.projectName"
                      :value="project.id"></el-option>
                  </el-select>
                </el-form-item>
                <el-button type="primary" @click="openDialog" class="custom-button"
                  style="margin-left: 26%;margin-bottom: 15px;">修改选中项目</el-button>
                <el-dialog v-model="dialogVisibleprojectxiugai" title="修改项目">
                  <el-form :model="currentProject">
                    <el-form-item label="项目名称">
                      <el-input v-model="currentProject.projectName"></el-input>
                    </el-form-item>
                    <el-form-item label="参与人数">
                      <el-input-number v-model="currentProject.projectPersonCount" :min="1"></el-input-number>
                    </el-form-item>
                  </el-form>
                  <div class="dialog-footer">
                    <el-button @click="dialogVisibleprojectxiugai = false">取 消</el-button>
                    <el-button type="primary" @click="submitDialog">确 定</el-button>
                  </div>
                </el-dialog>
              </div>
              <el-form-item label="报名截止时间">
                <el-date-picker v-model="From.deadline" type="date" placeholder="选择日期" aria-autocomplete="off"></el-date-picker>
              </el-form-item>
              <el-form-item label="选择修改组别">
                <el-select v-model="selectedGroupId" placeholder="请选择项目" @change="handleSelectChangegroup">
                  <el-option v-for="group in newGroupadd" :key="group.id" :label="group.groupname"
                    :value="group.id"></el-option>
                </el-select>
                <el-button type="primary" @click="openDialoggroup" class="custom-button"
                  style="margin-top: 15px;">修改选中组别</el-button>
                <el-dialog title="修改组别" v-model="dialogVisible" width="30%">
                  <el-form :model="currentGroup">
                    <el-form-item label="组别名称" label-width="120px">
                      <el-input v-model="currentGroup.groupname" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="参赛性别" label-width="120px">
                      <el-radio-group v-model="currentGroup.sex">
                        <el-radio :value="1" size="large">男</el-radio>
                        <el-radio :value="0" size="large">女</el-radio>
                        <el-radio :value="2" size="large">不限</el-radio>
                      </el-radio-group>
                    </el-form-item>
                    <el-form-item label="最小出生日期" label-width="120px">
                      <el-date-picker v-model="currentGroup.maxBirthDay" autocomplete="off"
                        type="date"></el-date-picker>
                    </el-form-item>
                    <el-form-item label="最大出生日期" label-width="120px">
                      <el-date-picker v-model="currentGroup.minBirthDay" autocomplete="off"
                        type="date"></el-date-picker>
                    </el-form-item>
                  </el-form>
                  <template #footer>
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitFormCategory">提交</el-button>
                  </template>
                </el-dialog>
              </el-form-item>
              <el-form-item label="联系电话">
                <el-input v-model="From.telephone" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="备注">
                <el-input type="textarea" v-model="From.mem" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item>
                <el-upload class="upload-drag" action="https://jsonplaceholder.typicode.com/posts/" multiple>
                  <el-button size="small" type="primary"
                    style="background-color: white;border: none; border-radius: 4px; padding: 10px 20px; font-size: 16px; font-weight: bold; margin-bottom: 10px; height: 40px;">
                    <Upload />
                  </el-button>
                  <div class="el-upload__tip">可上传多个文件</div>
                </el-upload>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" class="custom-button-end" @click="submitFormtitle">修改保存</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-card>
      </div>
    </el-container>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue';
import axios from 'axios'; // 导入 axios
import { useRoute } from 'vue-router'; // 导入路由
import { ElMessage } from 'element-plus';

const route = useRoute();

const id = route.query.id;

const From = ref({
  deadline:'',
  telephone:'',
  mem:''
})

//页面数据初始化
const eventForm = ref({
  projects: [],
  groups: []
});

const newProjectadd = ref([]);//用于存储要修改的项目
const newGroupadd = ref([]);//用于存储要修改的组别
const newMatchadd = ref([]);//用于存储要修改的比赛

const token = localStorage.getItem('adminToken'); // 从 localStorage 获取 token

const selectedProjectId = ref(null);// 用于存储当前选中的项目ID
const dialogVisibleprojectxiugai = ref(false);// 用于控制项目修改对话框的显示与隐藏
const currentProject = ref({ projectName: '', projectPersonCount: 0 });// 用于存储当前正在修改的项目数据

const selectedGroupId = ref(null);// 用于存储当前选中的组别ID
const currentGroup = ref({ groupname: '',sex:'', minBirthDay: '', maxBirthDay: '' });// 用于存储当前正在修改的组别数据
const dialogVisible = ref(false); // 控制修改组别对话框的显示与隐藏

//监视选中修改组别，获取id，获取对应项目信息
const handleSelectChangegroup = (id) => {
  const group = newGroupadd.value.find(p => p.id === id);
  if (group) {
    selectedGroupId.value = id;
    currentGroup.value = { ...group };
  }
};

//通过id打开对应修改组别对话框
const openDialoggroup = () => {
  if (selectedGroupId.value) {
    const group = newGroupadd.value.find(p => p.id === selectedGroupId.value);
    if (group) {
      currentGroup.value = { ...group };
      dialogVisible.value = true;
    }
  }
};

//关闭修改组别对话框,提交修改数据发送请求
const submitFormCategory = async () => {
  const index = newGroupadd.value.findIndex(p => p.id === selectedGroupId.value);
  if (index !== -1) {
    newGroupadd.value[index] = { ...currentGroup.value };
  }
  dialogVisible.value = false;
  const GroupSubmits = newGroupadd.value.map(group => ({
    id: group.id,
    sex: group.sex,
    groupname: group.groupname,
    minBirthDay: group.minBirthDay,
    maxBirthDay: group.maxBirthDay
  }));
  try {
    const token = localStorage.getItem('adminToken'); // 从 localStorage 获取 token
    const response = await axios.put(`http://back1.idcfengye.com:15173/competition/matchgroup`, GroupSubmits, {
      headers: {
        Authorization: `Bearer ${token}`,
      },
    });

    // 检查响应数据是否为数组
    if (Array.isArray(response.data)) {
      // 处理批量更新的响应
      const successCount = response.data.filter(item => item.success).length;
      if (successCount === response.data.length) {
        ElMessage.success('修改成功');
      } else {
        const errorMessages = response.data.filter(item => !item.success).map(item => item.msg).join(', ');
        ElMessage.error(`修改失败：${errorMessages}`);
      }
    } else if (response.data.success) {
      // 处理单个更新的响应
      ElMessage.success('修改成功');
    } else {
      ElMessage.error(`修改失败：${response.data.msg}`);
    }
  } catch (error) {
    ElMessage.error(`请求失败：${error.message}`);
    console.error(error);
  }
}

//监视选中修改项目，获取id，获取对应项目信息
const handleSelectChange = (id) => {
  const project = newProjectadd.value.find(p => p.id === id);
  if (project) {
    selectedProjectId.value = id;
    currentProject.value = { ...project };
  }
};

//通过id打开对应修改项目对话框
const openDialog = () => {  
  if (selectedProjectId.value) {
    const project = newProjectadd.value.find(p => p.id === selectedProjectId.value);
    if (project) {
      currentProject.value = { ...project };
      dialogVisibleprojectxiugai.value = true;
    }
  }
};

//关闭修改项目对话框,提交修改数据发送请求
const submitDialog = async () => {
  const index = newProjectadd.value.findIndex(p => p.id === selectedProjectId.value);
  if (index !== -1) {
    newProjectadd.value[index] = { ...currentProject.value };
  }
  dialogVisibleprojectxiugai.value = false;

  const ProjectSubmits = newProjectadd.value.map(project => ({
    id: project.id,
    projectName: project.projectName,
    projectPersonCount: project.projectPersonCount
  }));

  try {
    const token = localStorage.getItem('adminToken'); // 从 localStorage 获取 token
    const response = await axios.put(`http://back1.idcfengye.com:15173/competition/project`, ProjectSubmits, {
      headers: {
        Authorization: `Bearer ${token}`,
      },
    });

    // 检查响应数据是否为数组
    if (Array.isArray(response.data)) {
      // 处理批量更新的响应
      const successCount = response.data.filter(item => item.success).length;
      if (successCount === response.data.length) {
        ElMessage.success('修改成功');
      } else {
        const errorMessages = response.data.filter(item => !item.success).map(item => item.msg).join(', ');
        ElMessage.error(`修改失败：${errorMessages}`);
      }
    } else if (response.data.success) {
      // 处理单个更新的响应
      ElMessage.success('修改成功');
    } else {
      ElMessage.error(`修改失败：${response.data.msg}`);
    }
  } catch (error) {
    ElMessage.error(`请求失败：${error.message}`);
    console.error(error);
  }
};

const submitFormtitle = async () => {
  newMatchadd.value = newMatchadd.value.map(item => {
  if (item) {
    return {
      id: item.id,
      title: item.title,
      deadline: new Date(From.value.deadline),
      telephone: From.value.telephone,
      mem: From.value.mem,
      disabled: item.disabled
    };
  }
});

try {
  const token = localStorage.getItem('adminToken'); // 从 localStorage 获取 token
  const response = await axios.put(`http://back1.idcfengye.com:15173/competition/match`, newMatchadd.value, {
    headers: {
      Authorization: `Bearer ${token}`,
    },
  });
  if(response.data.success && response.status === 200){
    ElMessage.success('修改成功');
  }else if(!response.data.success && response.status === 501){
    ElMessage.error('修改失败');
  }
} catch (error) {
  ElMessage.error(`请求失败：${error.message}`);
  console.error(error);
}
}

// 赛事添加的数据
const resetForm = ref({
  eventName: '',
  registrationDeadline: '',
  contactPhone: '',
  remarks: '',
  disabled: ''
})

// 计算当天日期
const currentDate = computed(() => {
  const date = new Date();
  const year = date.getFullYear();
  const month = date.getMonth() + 1; // getMonth() 返回的月份是从0开始的，所以需要+1
  const day = date.getDate();

  return `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`;
});

// 判断手机号
function isValidPhoneNumber(phoneNumber) {
  const regex = /^\d{11}$/;
  return regex.test(phoneNumber);
}

  // 获取比赛列表
  onMounted(async () => {
    const matchId = id;
    try {
      const response = await axios.get(`http://back1.idcfengye.com:15173/competition/project/${matchId}`, {
        headers: {
          Authorization: `Bearer ${token}`,
        },
      });
      if (response.status === 200 && response.data.success) {
        newProjectadd.value = response.data.project;
        // console.log(Form.newProject); // 打印 Form.newProject      
      };
    } catch (error) {
      if (error.response && error.response.status === 500) {
        ElMessage.error('服务器错误，请稍后再试');
      }
    }
    try {
      const response = await axios.get(`http://back1.idcfengye.com:15173/competition/match/${matchId}`, {
        headers: {
          Authorization: `Bearer ${token}`,
        },
      });
      if (response.status === 200 && response.data.success) {
        newMatchadd.value = response.data.match;
        // console.log(newMatchadd.value); // 打印 Form.newMatchGroup
      } else {
        console.log('No data returned:', response);
      }
    } catch (error) {
      if (error.response) {
        ElMessage.error('服务器错误，请稍后再试');
        console.error(error.response);
      } else if (error.request) {
        console.error(error.request);
      } else {
        console.error('Error', error.message);
      }
    }
    try {
      const response = await axios.get(`http://back1.idcfengye.com:15173/competition/matchgroup/${matchId}`, {
        headers: {
          Authorization: `Bearer ${token}`,
        },
      });
      if (response.status === 200 && response.data.success) {
        newGroupadd.value = response.data.matchgroup;
        // console.log(Form.group); // 打印 Form.group
      };
    } catch (error) {
      if (error.response) {
        ElMessage.error('服务器错误，请稍后再试');
        console.error(error.response);
      } else if (error.request) {
        console.error(error.request);
      } else {
        console.error('Error', error.message);
      }
    }
  });
</script>

<style scoped>


.event-form .el-form-item__label {
  color: black;
}

/* 为输入框、下拉框等设置灰色背景 */
.event-form .el-input__inner,
.event-form .el-select .el-input__inner,
.event-form .el-textarea__inner,
.event-form .el-date-editor .el-input__inner {
  background-color: #f5f5f5;
  color: black;
}

/* 自定义按钮样式 */
.custom-button {
  background-color: black;
  color: white;
}

/* 为标签设置灰色背景和黑色字体 */
.event-form .el-tag {
  background-color: #f5f5f5;
  color: black;
}

/* 设置卡片背景色 */
.box-card {
padding: 20px;
  border-radius:10px;
  background-color: #aacec6;
  width: 500px;
}

span {
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 28px;
  text-align: center;
  margin-bottom: 20px;
}

.main{
  display: flex;
  justify-content: center;
  align-items: center;
}

svg {
  height: 40px;
  color: black;
}

.custom-button-end {
  position: relative;
  /* right: 30px; */
  width: 400px;
  background-color: black;
}

.custom-group-input-container {
  width: 100%;
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  /* 添加一些间隔 */
}

.custom-group-tags-container {
  display: flex;
  flex-wrap: wrap;
}
</style>